package com.woniuxy.member.app.apiImpl;

import com.woniuxy.cloud.mall95.log.Log;
import com.woniuxy.coupon.client.CouponManageClient;
import com.woniuxy.coupon.client.CouponQueryClient;
import com.woniuxy.coupon.client.result.CouponDto;
import com.woniuxy.member.app.apiImpl.util.RequestUtil;
import com.woniuxy.member.client.CouponClient;
import com.woniuxy.member.infra.model.MemberCoupon;
import com.woniuxy.member.service.MemberCouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import result.Result;
import utils.Assert;

import java.util.Date;

@RequestMapping("/member")
@RestController
public class CouponApiImpl implements CouponClient {
    @Autowired
    private CouponQueryClient couponQueryClient;
    @Autowired
    private CouponManageClient couponManageClient;
    @Autowired
    private MemberCouponService memberCouponService;
    @Log("用户查询能兑换优惠卷")
    @Override
    public Result getStoreCoupon() {
        Integer storeId = RequestUtil.getStoreId();
        Result result = couponQueryClient.memberQueryCoupon(storeId);
        return result;
    }
    @Log("用户领取优惠卷")
    @Override
    public Result giveCoupon(Integer couponId) {
        Result result = couponManageClient.memberChangeCouponReceive(couponId);

        Assert.state(result.getFlag(),"业务繁忙");
        if (result.getFlag()){
            Result<CouponDto> couponDtoResult = couponQueryClient.queryCouponById(couponId);
            MemberCoupon memberCoupon = new MemberCoupon();
            memberCoupon.setMemberId(RequestUtil.getMemberId());
            memberCoupon.setCouponId(couponId);
            memberCoupon.setUseState("UNUSE");
            memberCoupon.setReceiveTime(new Date());
            memberCoupon.setExpirationTime(couponDtoResult.getData().getCouponEndTime());
            memberCouponService.save(memberCoupon);
        }
        return result;
    }
}
